<template>
  <div class="weather-container">
    <!-- 顶部导航栏 -->
    <div class="weather-header">
      <van-icon name="arrow-left" class="back-icon" @click="goBack" />
      <h1 class="page-title">天气详情</h1>
      <div class="empty-div"></div>
    </div>

    <!-- 当前天气信息卡片 -->
    <div class="current-weather-card">
      <div class="location-info">
        <van-icon name="location-o" class="location-icon" />
        <div class="location-content">
          <span class="location-text">{{ currentCity }}</span>
        </div>
        <van-button size="small" class="switch-city-btn" @click="switchCity">切换城市</van-button>
      </div>
      
      <div class="temperature-info">
        <div class="temperature-main">{{ currentTemperature }}°C</div>
        <div class="weather-desc">{{ weatherDescription }}</div>
      </div>

      <div class="weather-details">
        <div class="detail-item">
          <span class="detail-label">湿度</span>
          <span class="detail-value">{{ humidity }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">风向</span>
          <span class="detail-value">{{ windDirection }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">风力</span>
          <span class="detail-value">{{ windForce }}</span>
        </div>
      </div>
    </div>

    <!-- 三日天气预报 -->
    <div class="forecast-section">
      <h2 class="section-title">三日天气预报</h2>
      <div class="forecast-list">
        <div v-for="(day, index) in forecast" :key="index" class="forecast-item">
          <div class="forecast-date">{{ getDayOfWeek(index) }}</div>
          <div class="forecast-icon">
            <span class="weather-emoji-icon">{{ getWeatherIcon(day.type) }}</span>
          </div>
          <div class="forecast-type">{{ day.type }}</div>
          <div class="forecast-temp">{{ day.low }}°C / {{ day.high }}°C</div>
        </div>
      </div>
</div>



  <!-- 城市选择弹窗 -->
    <van-popup v-model:show="cityPopupVisible" position="bottom" >
      <div class="popup-header">
        <h3>选择城市</h3>
        <van-icon name="close" @click="closeCityPopup" class="close-icon-large" />
      </div>
      <div class="area-selector">
        <Area :area-list="areaList" v-model:value="selectedArea" @change="onAreaChange" :columns-num="2" :show-toolbar="false" />
      </div>
      <div class="popup-footer">
        <van-button type="primary" @click="confirmCitySelection" block>确定</van-button>
      </div>
    </van-popup>
  </div>
</template>

<script setup>
import { computed, ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { useWeatherStore } from '../store/weather';
import { Area, Toast } from 'vant';
import { areaList } from '@vant/area-data';

const router = useRouter();
const weatherStore = useWeatherStore();
const cityPopupVisible = ref(false);

// 选中的省市区代码
const selectedArea = ref(['', '', '']);
// 选中的城市名称
const selectedCityName = ref('北京');

// 组件挂载时获取天气数据
onMounted(async () => {
  await weatherStore.fetchWeatherData();
});

// 计算属性
const currentWeather = computed(() => weatherStore.currentWeather);
const currentCity = computed(() => weatherStore.location.city || '未知城市');
const forecast = computed(() => weatherStore.forecast || []);

// 当前温度
const currentTemperature = computed(() => {
  if (!currentWeather.value || !currentWeather.value.temperature) return '--';
  
  // 尝试将温度字符串转换为数字
  const tempString = currentWeather.value.temperature;
  const tempNumber = parseFloat(tempString.replace(/[^0-9.-]/g, ''));
  
  // 检查是否为有效数字
  if (isNaN(tempNumber)) return '--';
  
  return Math.round(tempNumber);
});

// 天气描述
const weatherDescription = computed(() => {
  if (!currentWeather.value || !currentWeather.value.type) return '未知';
  return currentWeather.value.type;
});

// 湿度
const humidity = computed(() => {
  if (!currentWeather.value || !currentWeather.value.humidity) return '--';
  return currentWeather.value.humidity.replace('%', '');
});

// 风向
const windDirection = computed(() => {
  if (!currentWeather.value || !currentWeather.value.wind) return '--';
  // 从风向风力字符串中提取风向
  const windMatch = currentWeather.value.wind.match(/^[\u4e00-\u9fa5]+/);
  return windMatch ? windMatch[0] : '--';
});

// 风力
const windForce = computed(() => {
  if (!currentWeather.value || !currentWeather.value.wind) return '--';
  // 从风向风力字符串中提取风力
  const windMatch = currentWeather.value.wind.match(/\d+级/);
  return windMatch ? windMatch[0] : '--';
});

// 获取星期几
function getDayOfWeek(index) {
  const days = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
  const today = new Date().getDay();
  return days[(today + index) % 7];
}

// 根据天气类型获取emoji图标
function getWeatherIcon(weatherType) {
  // 首先检查weatherType是否存在且有效
  if (!weatherType || typeof weatherType !== 'string') {
    return '🌤️';
  }
  
  // 使用与weather.js中相同的emoji图标映射
  const iconMap = {
    '晴': '☀️',
    '多云': '⛅',
    '阴': '☁️',
    '小雨': '🌦️',
    '中雨': '🌧️',
    '大雨': '⛈️',
    '雷阵雨': '⛈️',
    '雪': '❄️',
    '雾': '🌫️'
  };
  
  // 优先精确匹配
  if (iconMap[weatherType]) {
    return iconMap[weatherType];
  }
  
  // 然后尝试包含匹配
  for (const [key, icon] of Object.entries(iconMap)) {
    if (weatherType.includes(key)) {
      return icon;
    }
  }
  
  // 如果都匹配不到，返回默认图标
  return '🌤️';
}

// 返回上一页
function goBack() {
  router.back();
}

// 打开城市选择弹窗
function switchCity() {
  cityPopupVisible.value = true;
}

// 关闭城市选择弹窗
function closeCityPopup() {
  cityPopupVisible.value = false;
}

// 选择城市
async function selectCity(city) {
  await weatherStore.fetchWeatherData(city);
  cityPopupVisible.value = false;
}

// 处理地区选择变化
function onAreaChange(value) {
  let cityName = '';
  
  // 检查value的数据类型和结构
  if (typeof value === 'object' && value !== null) {
    // 处理用户提供的对象结构 {selectedValues: Array, selectedOptions: Array, ...}
    if (Array.isArray(value.selectedValues) && value.selectedValues.length >= 2) {
      const [provinceCode, cityCode] = value.selectedValues;
      if (provinceCode && cityCode && areaList.province_list && areaList.city_list) {
        cityName = areaList.city_list[cityCode] || areaList.province_list[provinceCode];
      }
    }
    // 同时也兼容直接使用selectedOptions获取城市名称
    else if (Array.isArray(value.selectedOptions) && value.selectedOptions.length >= 2) {
      const cityOption = value.selectedOptions[1]; // 第二个选项通常是城市
      if (cityOption && cityOption.text) {
        cityName = cityOption.text;
      }
    }
    // 处理旧的数组结构作为后备方案
    else if (Array.isArray(value) && value.length >= 2) {
      const [provinceCode, cityCode] = value;
      if (provinceCode && cityCode && areaList.province_list && areaList.city_list) {
        cityName = areaList.city_list[cityCode] || areaList.province_list[provinceCode];
      }
    }
  }
  
  // 更新选中的城市名，兜底处理
  selectedCityName.value = (cityName && cityName.trim()) || '北京';
}

// 确认城市选择
async function confirmCitySelection() {
  if (selectedCityName.value) {
    // 联级选择只到市，直接使用选中的城市名
    await selectCity(selectedCityName.value);
  } else {
    // 提示用户选择城市
    Toast('请选择一个城市');
  }
}

</script>

<style scoped>
.weather-container {
  padding: 0 20px;
  background-color: #f8f9fa;
  min-height: 100vh;
}

/* 顶部导航栏 */
.weather-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 0;
  background-color: white;
  position: sticky;
  top: 0;
  z-index: 10;
  margin: 0 -20px;
  padding: 20px;
}

.back-icon {
  font-size: 20px;
}

.page-title {
  font-size: 18px;
  font-weight: 600;
}

.empty-div {
  width: 20px;
}

/* 当前天气卡片 */
.current-weather-card {
  background: linear-gradient(135deg, #409eff 0%, #69b1ff 100%);
  border-radius: 16px;
  padding: 24px;
  color: white;
  margin-bottom: 24px;
  margin-top: 10px;
}

.location-info {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
}

.location-icon {
  margin-right: 8px;
}

.location-content {
  display: flex;
  align-items: center;
}

.location-text {
  font-size: 18px;
  font-weight: 500;
}

.switch-city-btn {
  background: rgba(255, 255, 255, 0.2);
  color: white;
  border: none;
  backdrop-filter: blur(10px);
}

.switch-city-btn:active {
  background: rgba(255, 255, 255, 0.3);
}

.temperature-info {
  text-align: center;
  margin-bottom: 24px;
}

.temperature-main {
  font-size: 60px;
  font-weight: bold;
  line-height: 1;
  margin-bottom: 8px;
}

.weather-desc {
  font-size: 16px;
  opacity: 0.9;
}

.weather-details {
  display: flex;
  justify-content: space-around;
  padding-top: 20px;
  border-top: 1px solid rgba(255, 255, 255, 0.2);
}

.detail-item {
  text-align: center;
}

.detail-label {
  display: block;
  font-size: 14px;
  opacity: 0.8;
  margin-bottom: 4px;
}

.detail-value {
  font-size: 18px;
  font-weight: 500;
}

/* 天气预报区域 */
.forecast-section {
  background-color: white;
  border-radius: 16px;
  padding: 20px;
  margin-bottom: 24px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 20px;
  color: #333;
}

.forecast-list {
  display: flex;
  justify-content: space-between;
}

.forecast-item {
  text-align: center;
  flex: 1;
}

.forecast-date {
    font-size: 14px;
    color: #666;
    margin-bottom: 8px;
  }



.forecast-icon {
  margin: 12px 0;
}

.weather-emoji-icon {
  font-size: 32px;
  line-height: 1;
}

.forecast-type {
  font-size: 14px;
  color: #333;
  margin-bottom: 4px;
}

.forecast-temp {
  font-size: 13px;
  color: #999;
}

/* 城市选择弹窗样式 */
.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #eee;
}

.popup-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
}

/* 放大关闭图标 */
.close-icon-large {
  font-size: 24px;
}

.area-selector {
  padding: 0 20px;
}

.popup-footer {
  padding: 20px;
  border-top: 1px solid #eee;
}

/* 自定义样式覆盖vant的默认样式 */
.van-area {
  background-color: transparent !important;
}

.van-area__columns {
  height: 40vh !important;
}
</style>